<template>
	<view class="device-page">
		<!-- 搜索区 -->
		<view class="search-wrap">
			<view class="search-box">
				<u-icon name="search"></u-icon>
				<input class="search-input" v-model="keyword" placeholder="输入SIM卡号搜索"
					placeholder-class="search-placeholder" @confirm="onSearch" />
				<view class="clear" v-if="keyword" @click="keyword=''">✕</view>
			</view>
			<button class="filter-btn" @click="openFilter">筛选</button>
		</view>
		<view class="" style="height: 90rpx;"></view>
		<!-- SIM卡列表 -->
		<view class="sim-list">

			<view class="sim-item" style="position: relative;margin-bottom: 16rpx;" v-for="(item, index) in simList"
				:key="index">
				<!-- 		<label class="custom-checkbox" @click="handleSelect(item.iccid)">
					<view class="checkbox-display" :class="{ checked: selectedItems.includes(item.iccid) }">
						<u-icon v-if="selectedItems.includes(item.iccid)" name="checkmark" color="#fff"
							size="20"></u-icon>
					</view>
				</label> -->
				<view class="sim-info">
					<view class="sim-header" v-if="item.msisdn" style="margin-bottom: 16rpx;">
						<text class="sim-number">{{ item.msisdn }}</text>
					</view>
					<view class="sim-details">
						<!-- <view class="detail-row">
							<text class="label">位置：</text>
							<text class="value">{{ item.packageName }}</text>
						</view> -->
						<view class="detail-row" v-if="item.packageName">
							<text class="label">套餐名称：</text>
							<text class="value">{{ item.packageName }}</text>
						</view>
						<view class="detail-row">
							<text class="label">有效期：</text>
							<text class="value">{{ item.endTime || '待激活'}}</text>
						</view>
						<view class="detail-row" v-if="item.state">
							<text class="label">状态：</text>
							<text class="status" :style="{ color: getStatusColor(item.state) }">
								{{ item.state }}（{{item.operator}}）
							</text>
						</view>
					</view>
				</view>
				<button v-if="item.iccid && item.state != '已销户'" style="position: absolute;right: 20rpx;bottom: 20rpx;"
					class="recharge-btn" @click="recharge(item)">一键充值</button>
			</view>
			<view class="" style=" padding-top: 150rpx;">
				<u-empty v-if="simList.length === 0" mode="data">
				</u-empty>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<!-- 		<view class="footer-bar">
						<label class="custom-checkbox all-select" @click="toggleAll">
				<view class="checkbox-display" :class="{ checked: isAllSelected }">
					<u-icon v-if="isAllSelected" name="checkmark" color="#fff" size="20"></u-icon>
				</view>
				<text class="all-text">全选 ({{ selectedCount }}/{{ total }})</text>
			</label>
			<view class="total-price">
				总计：{{ totalPrice }} 元
			</view>
			<view class="">

			</view>
			<button class="recharge-btn" @click="recharge">一键充值</button>
		</view> -->
	</view>
</template>

<script>
	import {
		iccListApi,
		wechatPlaceOrderApi,
		queryOrderNoApi,
		deviceListApi
	} from '@/api/index.js';
	export default {
		data() {
			return {
				pageFlag: false,
				keyword: '',
				selectedItems: [],
				simList: [
					// {
					// 	simId: '1',
					// 	simNumber: '89860473102070388234',
					// 	address: '上海市浦东新区',
					// 	expireDate: '2022-11-26 10:00:00',
					// 	status: '已激活（中国移动 上海）'
					// },
					// {
					// 	simId: '2',
					// 	simNumber: '89860473102070384276',
					// 	address: '浙江省杭州市',
					// 	expireDate: '2022-11-22 00:03:25',
					// 	status: '已激活（中国移动 上海）'
					// },
					// {
					// 	simId: '3',
					// 	simNumber: '89860473102070386495',
					// 	address: '广东省深圳市',
					// 	expireDate: '2022-11-25 14:19:16',
					// 	status: '已激活（中国移动 上海）'
					// },
					// {
					// 	simId: '4',
					// 	simNumber: '89860473102070386478',
					// 	address: '北京市朝阳区',
					// 	expireDate: '2022-12-13 08:29:42',
					// 	status: '已激活（中国移动 上海）'
					// },
					// {
					// 	simId: '5',
					// 	simNumber: '89860454092090092328',
					// 	address: '江苏省南京市',
					// 	expireDate: '2022-12-21 07:35:47',
					// 	status: '已激活（中国移动 上海）'
					// }
				],
				total: 0,
				totalPrice: 0,
				isAllSelected: false,
				searchData: {
					pageNum: 1,
					pageSize: 10
				}
			};
		},
		computed: {
			filteredList() {
				return !this.keyword ? this.simList : this.simList.filter(item => item.simNumber.includes(this.keyword));
			},
			// total() {
			// 	return this.simList.length;
			// },
			selectedCount() {
				return this.selectedItems.length;
			}
		},
		onLoad() {
			this.iccList();
		},
		onReachBottom() {
			if (!this.pageFlag) {
				if (this.searchData.pageNum * this.searchData.pageSize > this.total) return
				this.searchData.pageNum += 1;
				this.iccList(true)
			}
			console.log('触底');
		},
		onHide() {
			// console.log('切换页面');
			this.pageFlag = false
			this.searchData.pageNum = 1
		},
		methods: {
			// 流量列表
			async iccList(next) {
				uni.showLoading({
					title: '数据加载中'
				})
				try {
					const res = await deviceListApi(this.searchData);
					console.log(res, 'res-流量列表');
					if (res.code === 200) {
						if (this.searchData.pageNum === 1 && res.rows.length === 0) {
							this.simList = [];
							this.total = 0;
						}
						this.total = res.total;
						if (res.rows && res.rows.length > 0) {
							const iccids = next ?
								this.simList.concat(res.rows) :
								res.rows
							this.simList = iccids
						} else {
							if (next) {
								this.pageFlag = true
							}
						}
					}
				} catch {

				} finally {
					uni.hideLoading();
				}

			},
			handleSelect(simId) {
				const index = this.selectedItems.indexOf(simId);
				if (index === -1) this.selectedItems.push(simId);
				else this.selectedItems.splice(index, 1);
				this.updateAllSelection();
			},
			toggleAll() {
				if (this.isAllSelected) this.selectedItems = [];
				else this.selectedItems = this.simList.map(item => item.simId);
				this.isAllSelected = !this.isAllSelected;
			},
			updateAllSelection() {
				this.isAllSelected = this.selectedItems.length === this.simList.length;
			},
			// 充值
			async recharge(item) {
				// if (!this.selectedItems.length) {
				// 	uni.showToast({
				// 		title: '请先选择要充值的SIM卡',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }
				console.log(item, 'iccId');
				const res = await wechatPlaceOrderApi({
					iccId: item.iccid
				});
				console.log(res, 'res');
				if (res.code === 200) {
					wx.requestPayment({
						timeStamp: res.data.timeStamp, //后端返回的时间戳
						nonceStr: res.data.nonceStr, //后端返回的随机字符串
						package: res.data.package, //后端返回的prepay_id
						signType: res.data.signType, //后端签名算法,根据后端来,后端MD5这里即为MD5
						paySign: res.data.paySign, //后端返回的签名
						success: (result) => {
							console.log('用户支付扣款成功', result)
							this.queryOrderNo(res.data.orderNo, 1);
						},
						fail: (err) => {
							console.log('用户支付扣款失败', err)
							this.queryOrderNo(res.data.orderNo, 0);
						}
					})
				}
				// uni.showToast({
				// 	title: '开始充值...',
				// 	icon: 'success'
				// });
			},
			// 查询微信支付订单API（用户支付完调用，可根据返回的支付状态按需循环调用）
			async queryOrderNo(orderNo, type) {
				const res = await queryOrderNoApi(orderNo);
				console.log(res, 'res');
				if (type === 1) {
					uni.showModal({
						title: '提示',
						content: res.msg,
						showCancel: false,
						success: (resp) => {
							if (resp.confirm) {
								uni.redirectTo({
									url: '/pages/myFlow/myFlow'
								})
							}
						}
					})
				}
			},
			getStatusColor(status) {
				// console.log(status);
				if (!status) return '#f56c6c'
				return status.includes('已销户') ? '#f56c6c' : '#0081ff';
			}
		}
	};
</script>

<style lang="scss">
	.device-page {
		min-height: 100vh;
		background: #f6f7f8;
		position: relative;
		padding-bottom: 180rpx;
	}

	.search-wrap {
		display: flex;
		align-items: center;
		padding: 16rpx 18rpx;
		gap: 14rpx;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		background: #fff;
		z-index: 99999;
	}

	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 50rpx;
		padding: 10rpx 16rpx;
		box-shadow: 0 6rpx 18rpx rgba(24, 35, 50, 0.04);
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
	}

	.search-placeholder {
		color: #bfc6cc;
	}

	.clear {
		font-size: 22rpx;
		color: #999;
		padding: 6rpx;
	}


	/* 筛选按钮 */
	.filter-btn {
		background: #ffffff;
		border-radius: 12rpx;
		padding: 0rpx 18rpx;
		font-size: 26rpx;
		color: #0081ff;
		box-shadow: 0 6rpx 18rpx rgba(254, 84, 99, 0.06);
	}

	/* SIM卡列表 */
	.sim-list {
		margin: 24rpx;
		// background: #fff;
		overflow: hidden;
	}

	.sim-item {
		display: flex;
		padding: 32rpx;
		border-bottom: 1px solid #eee;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 10rpx 25rpx rgba(0, 0, 0, 0.05);
	}

	.custom-checkbox {
		display: flex;
		align-items: center;
		margin-right: 24rpx;
		position: relative;
	}

	.checkbox-display {
		width: 44rpx;
		height: 44rpx;
		border: 2rpx solid #0081ff;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s ease;

		&.checked {
			background-color: #0081ff;
			border-color: #0081ff;
		}
	}

	.sim-number {
		font-size: 32rpx;
		color: #222;
		font-weight: 600;
		// margin-bottom: 16rpx;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
	}

	.sim-details {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.label {
		color: #888;
		width: 130rpx;
		font-weight: 500;
	}

	.value {
		color: #555;
		flex: 1;
	}

	.status {
		font-size: 28rpx;
		font-weight: 600;
	}

	/* 底部操作栏 */
	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 24rpx 32rpx 60rpx 32rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 -10rpx 25rpx rgba(0, 0, 0, 0.05);
		z-index: 10;
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
	}

	.all-select {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
	}

	.all-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 12rpx;
		font-weight: 500;
	}

	.total-price {
		font-size: 30rpx;
		color: #0081ff;
		font-weight: 600;
		flex: 1;
		text-align: center;
	}

	/* 一键充值按钮渐变圆润 */
	.recharge-btn {
		background: linear-gradient(135deg, #0081ff, #00c6ff);
		color: #fff;
		border-radius: 30rpx;
		padding: 14rpx 36rpx;
		font-size: 30rpx;
		line-height: 1;
		font-weight: 600;
		box-shadow: 0 6rpx 20rpx rgba(0, 129, 255, 0.3);
		transition: transform 0.2s ease, box-shadow 0.2s ease;

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 4rpx 12rpx rgba(0, 129, 255, 0.25);
		}
	}
</style>